package thread.call;

import java.util.concurrent.*;

/**
 * @author yuisama
 * @date 2022/07/13 11:12
 **/
public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        // 接收call方法的返回值使用FutureTask对象
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        // Thread类接收Callable接口必须通过FutureTask类
//        Thread t = new Thread(futureTask);
//        t.start();
        ExecutorService pool = Executors.newFixedThreadPool(3);
        // FutureTask就是Future接口的子类，Future接口就是搭配Callable接口使用的，来接收Callable的返回值
        Future<Integer> callResult = pool.submit(callable);
        // get方法会阻塞当前线程，直到call方法执行完毕，才恢复执行
        int result = callResult.get();
        System.out.println("子线程执行结束，result = " + result);
    }
}